package com.hmdp.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

public class SimpleRedisLock implements ILock {
    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString() + "-";
    private String name;
    private StringRedisTemplate stringRedisTemplate;
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
        UNLOCK_SCRIPT.setResultType(Long.class);
    }

    public SimpleRedisLock(String name, StringRedisTemplate stringRedisTemplate) {
        this.name = name;
        this.stringRedisTemplate = stringRedisTemplate;
    }


    //TODO:初代分布式锁

//    @Override
//    public boolean tryLock(long timeoutSec) {
//        //TODO:获取线程id
//        long threadId = Thread.currentThread().getId();
//
//        //TODO:尝试获取锁
//            //todo:key为锁名称，value为线程id，timeout为锁的过期时间
//        Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX+name, threadId+"", timeoutSec, TimeUnit.SECONDS);
//        return lock;
//    }
//
//    @Override
//    public void unlock() {
//        //TODO：释放锁
//        stringRedisTemplate.delete(KEY_PREFIX+name);
//
//    }
//    //TODO:升级分布式锁（防止误删）
//@Override
//public boolean tryLock(long timeoutSec) {
//    //TODO:获取线程id
////    long threadId = Thread.currentThread().getId();
//    //使用UUID来区分不同的jvm+线程
//    //表示更改为UUID+线程id
//    String threadId = ID_PREFIX+Thread.currentThread().getId();
//
//
//    //TODO:尝试获取锁
//    //todo:key为锁名称，value为线程id，timeout为锁的过期时间
//    Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX+name, threadId+"", timeoutSec, TimeUnit.SECONDS);
//    return lock;
//}

//    //释放所示先进行判断，是否为当前线程的锁，如果是则释放锁
//    @Override
//    public void unlock() {
//        //获取当前的表示
//        String threadId = ID_PREFIX+Thread.currentThread().getId();
//        //获取redis中的锁
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX+name);
//        //判断是否为当前线程的锁
//        if (threadId.equals(id)) {
//            //释放锁
//            stringRedisTemplate.delete(KEY_PREFIX+name);
//        }
//        //失败，不释放锁
//    }
    //TODO:升级分布式锁（使用Lua脚本确保释放锁和判段是否为同一把锁原子性）
@Override
public boolean tryLock(long timeoutSec) {
    //TODO:获取线程id
   String threadId  = ID_PREFIX+Thread.currentThread().getId();
   //TODO:尝试获取锁
   //todo:key为锁名称，value为线程id，timeout为锁的过期时间
   Boolean lock = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX+name, threadId+"", timeoutSec, TimeUnit.SECONDS);
   return lock;
}
    //释放锁
    @Override
    public void unlock() {
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX+name),
                ID_PREFIX+Thread.currentThread().getId());


    }

}
